from time import sleep

from selenium.webdriver.common.by import By

from qiyeweixin_testing.page_object.base_page import BasePage

from qiyeweixin_testing.until.log_utils import logger


class AddressBookPage(BasePage):
    # 添加成员
    __ADD_MEMBER = (By.LINK_TEXT, "添加成员")
    __NAME = (By.ID, "username")
    __ACCT_ID = (By.ID, "memberAdd_acctid")
    __MAIL = (By.ID, "memberAdd_biz_mail")
    __PHONE = (By.ID, "memberAdd_phone")
    __SAVE = (By.XPATH, "//*[text()='保存']")
    # 添加部门
    __ADD_INFO = (By.XPATH, "//*[text()='添加']/..")
    __ADD_DEPARTMENT = (By.XPATH, "//*[text()='添加部门']")
    __DEPARTMENT_NAME = (By.XPATH, "//*[text()='部门名称']/..//input")
    __SELECTOR_DEPARTMENT = (By.XPATH, "//*[text()='选择所属部门']/..")
    __SELECTOR_KANGXI = (By.ID, "1688856156347810_anchor")
    __DEPARTMENT_SAVE = (By.XPATH, "//*[text()='确定']")

    def add_member_btn(self):
        self.wait_until_click(self.__ADD_MEMBER).click()

        return AddressBookPage(self.driver)

    def add_member(self, user_info):
        # 姓名
        self.do_find(self.__NAME).click()
        self.do_send_keys(user_info.get("name"), self.__NAME)
        # 帐号
        self.do_find(self.__ACCT_ID).click()
        self.do_send_keys(user_info.get("phone_number"), self.__ACCT_ID)
        # 邮箱
        self.do_find(self.__MAIL).click()
        self.do_send_keys(user_info.get("phone_number"), self.__MAIL)
        # 手机
        self.do_find(self.__PHONE).click()
        self.do_send_keys(user_info.get("phone_number"), self.__PHONE)

        logger.info(f'姓名：{user_info.get("name")}, 帐号：{user_info.get("phone_number")}')

        return AddressBookPage(self.driver)

    def save(self):
        self.do_find(self.__SAVE).click()

        from qiyeweixin_testing.page_object.home_page import HomePage
        return HomePage(self.driver)

    def get_add_result(self, user_info):
        return self.do_find((By.XPATH, f"//*[text()='{user_info.get('name')}']")).text

    def add_department_btn(self):
        self.do_find(self.__ADD_INFO).click()
        self.wait_until_click(self.__ADD_DEPARTMENT).click()

        return AddressBookPage(self.driver)

    def add_department(self, department):
        # 填写部门信息
        self.do_send_keys(department, self.__DEPARTMENT_NAME)
        # 选择所属部门
        self.do_find(self.__SELECTOR_DEPARTMENT).click()
        self.do_finds(self.__SELECTOR_KANGXI)[1].click()

        return AddressBookPage(self.driver)

    def department_save(self):
        self.do_find(self.__DEPARTMENT_SAVE).click()

        from qiyeweixin_testing.page_object.home_page import HomePage
        return HomePage(self.driver)

    def get_add_department(self, department):
        if ele_flag := self.wait_until_element((By.XPATH, f"//*[text()='{department}']")):
            return self.do_find((By.XPATH, f"//*[text()='{department}']")).text
        else:
            raise Exception(f'address_book_page: line78 ele_flag no such Element')
